package helpers;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcelHelper {
	public static void read(String inputFile) 
		throws IOException {
		File inputWorkbook = new File(inputFile);
	    Workbook w;
	    try {
	      w = Workbook.getWorkbook(inputWorkbook);
	      // Get the first sheet
	      Sheet sheet = w.getSheet(0);
	      // Loop over first 10 column and lines

	      for (int j = 0; j < sheet.getColumns(); j++) {
	        for (int i = 0; i < sheet.getRows(); i++) {
	          Cell cell = sheet.getCell(j, i);
	          CellType type = cell.getType();
	          if (cell.getType() == CellType.LABEL) {
	            System.out.println("I got a label "
	                + cell.getContents());
	          }

	          if (cell.getType() == CellType.NUMBER) {
	            System.out.println("I got a number "
	                + cell.getContents());
	          }

	        }
	      }
	    } catch (BiffException e) {
	      e.printStackTrace();
	    }
	}
	
	public static List<String> readColumn(String inputFile, int column) 
		throws IOException {
		List<String> lst = new ArrayList<String>();
		
		File inputWorkbook = new File(inputFile);
	    Workbook w;
	    try {
			w = Workbook.getWorkbook(inputWorkbook);
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines

	        for (int i = 0; i < sheet.getRows(); i++) {
	          Cell cell = sheet.getCell(column, i);
	          CellType type = cell.getType();
	          if (cell.getType() == CellType.LABEL) {
	            lst.add(cell.getContents());
	          }
	
	        }
	    
	    } catch (BiffException e) {
	      e.printStackTrace();
	    }
		
		return lst;
	}
	
	public static List<String> readColumnFromInputStream(InputStream inp, int column) 
		throws IOException {
		List<String> lst = new ArrayList<String>();
		
	    Workbook w;
	    try {
			w = Workbook.getWorkbook(inp);
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines
	
	        for (int i = 0; i < sheet.getRows(); i++) {
	          Cell cell = sheet.getCell(column, i);
	          CellType type = cell.getType();
	          if (cell.getType() == CellType.LABEL) {
	            lst.add(cell.getContents());
	          }
	
	        }
	    
	    } catch (BiffException e) {
	      //e.printStackTrace();
	    }
		
		return lst;
	}
	
	public static void main(String[] args) {
		try {
			List<String> lst = ReadExcelHelper.readColumn("C:/Users/User/Desktop/linhtinh/demoImportExcel.xls", 0);
		    System.out.println(StringHelper.listToString(lst, ","));
		} catch (Exception e) {
			// TODO: handle exception
		}
	    
	}
}
